const pianoKeys = document.querySelectorAll('.piano-keys .key');
const volumeSlider = document.querySelector(".volume-slider input");
const keysCheckbox = document.querySelector(".keys-checkbox input");

let allKeys = []
let audio = new Audio('tunes/a.wav')

const playTune = (key) => {
    //根据按键选择对应音频播放
    audio.src = `tunes/${key}.wav`
    audio.play()
    //获取按下的按键
    const clickedKey = document.querySelector(`[data-key="${key}"]`)
    //添加案件效果
    clickedKey.classList.add('active')
    //150ms后取消按键效果
    setTimeout(() => {
        clickedKey.classList.remove('active')
    }, 150)
}

pianoKeys.forEach(key => {
    //按键监听
    allKeys.push(key.dataset.key)
    key.addEventListener('click', () => {
        playTune(key.dataset.key)
    })
})

const handleVolume = (e) => {
    audio.volume = e.target.value
}

const pressedKey = (e) => {
    //只获取特定按键
    if (allKeys.includes(e.key)) playTune(e.key)
}

const showHidekeys = () => {
    pianoKeys.forEach(key =>
        key.classList.toggle('hide')
    )
}

keysCheckbox.addEventListener("click", showHidekeys)
volumeSlider.addEventListener("input", handleVolume)
document.addEventListener("keydown", pressedKey)